package cn.ctyun.ipush.controller;

import cn.ctyun.ipush.constant.ResultInfo;
import cn.ctyun.ipush.dto.ResultDto;
import cn.ctyun.ipush.model.*;
import cn.ctyun.ipush.service.impl.JobService;
import cn.ctyun.ipush.service.*;
import cn.ctyun.ipush.utils.ConfigUtils;
import cn.ctyun.ipush.utils.DBUtils;
import cn.ctyun.ipush.utils.DataUtils;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.vo.ExcelVo;
import cn.ctyun.ipush.vo.PictureVo;
import cn.ctyun.ipush.vo.TaskVo;
import cn.ctyun.ipush.web.user.bo.City;
import cn.ctyun.ipush.web.user.bo.UserModel;
import com.alibaba.fastjson.JSON;
import com.aspose.cells.Workbook;
import com.dexcoder.dal.JdbcDao;
import com.dexcoder.dal.build.Criteria;
import org.apache.commons.lang.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-7-13
 * Time: 下午4:11
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class TaskJobController {

    /* 日志对象 */
    private final Logger LOG = LoggerFactory.getLogger(TaskJobController.class);

    @Autowired
    private TaskDetailService taskDetailService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ExcelService excelService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private DataSourceService dataSourceService;

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    private ScheduleJobService scheduleJobService;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private JobService jobService;


    //------------------------------------------------------------------------

    /**
     * 用于进入页面后，显示数据
     */
    @RequestMapping(value = "taskIntoPage", method = RequestMethod.GET)
    public ModelAndView intoPage(HttpSession session, HttpServletRequest request) {

        UserModel systemUserModel = new UserModel();
        try {
            Object o = session.getAttribute("userInfo");
            if (o != null) {
                systemUserModel = (UserModel) o;

                //得到用户对应的任务对象
                TaskModel taskModel = new TaskModel();
                taskModel.setCreateUserid(systemUserModel.getUserModelId());
                List<TaskModel> taskModelList = taskService.queryList(taskModel);

                //得到用户的任务详情对象
                List<TaskDetailModel> taskDetailModelList = new ArrayList<TaskDetailModel>();
                if (taskModelList != null) {
                    for (TaskModel taskModel1 : taskModelList) {
                        TaskDetailModel taskDetailModel = taskDetailService.querySingleResult(taskModel1.getTaskDetailId());
                        taskDetailModelList.add(taskDetailModel);
                    }
                }
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("taskList", taskDetailModelList);
                return new ModelAndView("taskManager", data);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            //没有登录。。。。跳回login
            return new ModelAndView("login", null);
        }
    }

    @RequestMapping(value = "taskAdd", method = RequestMethod.POST)
    @Transactional
    public ModelAndView taskAdd(HttpSession session, HttpServletRequest request, @RequestParam("excelFile") MultipartFile[] files) {

        UserModel systemUserModel = new UserModel();
        String msg = "";
        boolean isSave = true;
        try {
            Object o = session.getAttribute("userInfo");

            if (o != null) {
                systemUserModel = (UserModel) o;
                String taskName = request.getParameter("taskName");
                String cronExpression = request.getParameter("cronExpression");//@分割
                String taskDesc = request.getParameter("taskDesc");
                String isAutoRun = request.getParameter("isAutoRun");
                String dataSource = request.getParameter("dataSource");//"c465317882254dcf8806d0edc67386a1";//request.getParameter("dataSource");//todo
                String emailRule = request.getParameter("emailRule");//"23bfcae58e4e43b69fbff07acc332144";//request.getParameter("emailRule");//todo
                String sheetNames = request.getParameter("sheetNames");
                String picturePix = "200";//request.getParameter("picturePix");
                //v1.1补充
                String emailOption = request.getParameter("isSendEmail");
                String emailSubject = request.getParameter("emailSubject");
                String emailContent = request.getParameter("emailContent");
                String emailIsSendExcel = request.getParameter("isSendExcel");
                String emailIsSendPicture = request.getParameter("isSendPicture");

                String isSendYixin = request.getParameter("isSendYixin");
                String yixinNames = request.getParameter("yixinNames");


                if (emailOption != null) {
                    if (StringUtils.isEmpty(emailSubject)) {
                        msg = "邮件主题不能为空";
                        isSave = false;
                    }
                    if (StringUtils.isEmpty(emailContent)) {
                        msg = "邮件内容不能为空";
                        isSave = false;
                    }
                }

                if (isSendYixin != null) {
                    if (StringUtils.isEmpty(yixinNames)) {
                        msg = "易信接收人不能为空";
                        isSave = false;
                    }
                }
                //v1.1


                //sheetNames
                if (StringUtils.isEmpty(sheetNames)) {
                    msg = "sheet名称不为能空";
                    isSave = false;
                }
                //文件判断
                List<String> sqlList = new ArrayList<String>();
                if (null == files || files[0].getOriginalFilename().isEmpty()) {
                    isSave = false;
                    msg = "上传的Excel文件不能为空";
                } else {
                    //检测是否是Excel文件格式
                    ResultDto resultDto = DataUtils.isFileFormatOk(files[0].getInputStream());
                    if (resultDto.getStatus().equals(ResultInfo.failure)) {
                        msg = (String) resultDto.getInfo();
                        isSave = false;
                    }
                    if (StringUtils.isEmpty(sheetNames)) {
                        msg = "sheet名称不为能空";
                        isSave = false;
                    } else {
                        //检测sheet名称是否存在,如果返回成功，返回map 包括 table 字段
                        String[] sheetNamesTmp = sheetNames.split("\\*");
                        List<String> sheetListTmp = new ArrayList<String>();
                        for (String tmp : sheetNamesTmp) {
                            sheetListTmp.add(tmp);
                        }
                        resultDto = DataUtils.isSheetNamesExist(files[0].getInputStream(), sheetListTmp);
                        if (resultDto.getStatus().equals(ResultInfo.failure)) {
                            msg = (String) resultDto.getInfo();
                            isSave = false;
                        } else {
                            Map<String, String> sqlMap = (Map<String, String>) resultDto.getInfo();
                            for (Map.Entry entry : sqlMap.entrySet()) {
                                sqlList.add(entry.getValue() + " from " + entry.getKey());
                            }
                        }
                        // Excel中表名和字段在数据库是否存在
                        DataSourceModel dsm = new DataSourceModel();
                        dsm.setIsDeleted("0");
                        dsm.setDataSourceModelId(dataSource);
                        dsm = jdbcDao.querySingleResult(dsm);
                        for (String sql : sqlList) {
                            resultDto = DBUtils.isOracleConectionSuccess(dsm.getDataSourceUrl(), dsm.getUserName(), dsm.getDsPassword(), null, sql);
                            if (resultDto.getStatus().equals(ResultInfo.failure)) {
                                isSave = false;
                                msg = (String) resultDto.getInfo();
                                break;
                            }
                        }
                    }
                }

                //taskDetailModel 判断
                TaskDetailModel taskDetailModel = new TaskDetailModel();

                //判断是否为空
                if (StringUtils.isEmpty(taskName)) {
                    msg = "任务名称不为能空";
                    isSave = false;
                } else {
                    taskDetailModel.setTaskAliasName(taskName);
                }
                if (StringUtils.isEmpty(cronExpression)) {
                    msg = "时间表达式不能为空";
                    isSave = false;
                } else {
                    try {
                        //是否是Cron表达式
                        for (String cron : cronExpression.split("@")) {
                            //表达式调度构建器
                            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
                        }
                        //判断是否存在且合理，cron在一个地市间隔为3分钟
                        List<TaskDetailModel> taskDetailModelList = taskService.getAllTaskDetailByCityId(systemUserModel.getCity());
                        if (taskDetailModelList != null && taskDetailModelList.size() > 0) {
                            boolean isValid = true;
                            ResultDto resultDto = new ResultDto();
                            for (String cron : cronExpression.split("@")) {
                                resultDto = DateUtils.isCronNoExistAndIsLegal(taskDetailModelList, cron);
                                if (resultDto.getStatus() == ResultInfo.failure) {
                                    msg = cron + " " + (String) resultDto.getInfo();
                                    isSave = false;
                                    break;
                                }
                            }
                        }
                        taskDetailModel.setCronExpression(cronExpression);
                    } catch (Exception ex) {
                        LOG.error(ex.getMessage());
                        msg = "Cron表达式错误";
                        isSave = false;
                    }
                }
                taskDetailModel.setTaskDesc(taskDesc);
                taskDetailModel.setIsAutoRun(isAutoRun);
                if (isAutoRun.equals("1")) { //自动执行
                    taskDetailModel.setTaskStatus("1");
                } else { //手动执行
                    taskDetailModel.setTaskStatus("0");
                }

                City city = new City();
                city.setCityId(systemUserModel.getCity());
                city = jdbcDao.querySingleResult(city);
                taskDetailModel.setTaskGroupName(city.getCityName());

                //任务数限制
                int userTaskNumsLimit = Integer.parseInt(ConfigUtils.getStringValue("userTaskNumsLimit"));
                TaskModel taskModellimit = new TaskModel();
                taskModellimit.setIsDeleted("0");
                taskModellimit.setCreateUserid(systemUserModel.getUserModelId());
                List<TaskModel> taskModelListlimit = jdbcDao.queryList(taskModellimit);
                if (taskModelListlimit.size() > 0) {
                    if (userTaskNumsLimit == taskModelListlimit.size()) {
                        msg = "任务数已达到最大值";
                        isSave = false;
                    }
                }

                if (isSave) {
                    //文件保存
                    String fileName = null; //原始文件名
                    String filePath = null; //完整的文件路径
                    String createUserid = systemUserModel.getUserModelId(); //创建用户ID
                    String excelName = null;//修改后的文件名 createUserId_filename

                    // Root Directory.
                    String uploadRootPath = request.getRealPath("/") + "upload";
                    uploadRootPath = ConfigUtils.getStringValue("excelTemplateAddress");
                    File uploadRootDir = new File(uploadRootPath);
                    // Create directory if it not exists.
                    if (!uploadRootDir.exists()) {
                        uploadRootDir.mkdirs();
                    }
                    List<File> uploadedFiles = new ArrayList<File>();
                    for (int i = 0; i < files.length; i++) {
                        MultipartFile file = files[i];
                        // Client File Name
                        String name = file.getOriginalFilename();
                        fileName = name;
                        LOG.info("Client File Name = " + name);
                        if (name != null && name.length() > 0) {
                            try {
                                byte[] bytes = file.getBytes();
                                // Create the file on server
                                filePath = uploadRootDir.getAbsolutePath() + File.separator + createUserid + "_" + DateUtils.timestampToDataString(System.currentTimeMillis()) + "_" + name;
                                excelName = createUserid + "_" + DateUtils.timestampToDataString(System.currentTimeMillis()) + "_" + name;
                                File serverFile = new File(filePath);
                                // Stream to write data to file in server.
                                BufferedOutputStream stream = new BufferedOutputStream(
                                        new FileOutputStream(serverFile));
                                stream.write(bytes);
                                stream.close();
                                uploadedFiles.add(serverFile);
                                LOG.info("Write file: " + serverFile);
                            } catch (Exception e) {
                                LOG.error(e.getMessage());
                                LOG.error("Error Write file: " + name);
                            }
                        }
                    }
                    //Excel store to DB
                    ExcelModel excelModel = new ExcelModel();
                    excelModel.setExcelPath(filePath);
                    excelModel.setTemplateName(fileName);
                    excelModel.setExcelName(excelName);
                    excelModel.setCreateUserid(createUserid);
                    StringBuffer stringBuffer = new StringBuffer();
                    for (String sql : sqlList) {
                        stringBuffer.append(sql + "$");
                    }
                    String sqlDb = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                    excelModel.setExcelTableFields(sqlDb);
                    //excelModel.setSheetNames(sheetNames);

                    ExcelVo excelVo = new ExcelVo();
                    excelVo.setExcelName(excelName);
                    String excelId = null;
                    if (!excelService.isExist(excelVo)) {
                        excelId = excelService.save(excelModel);
                        //保存图片的分辨率以及sheet页名称
                        PictureModel pictureModel = new PictureModel();
                        pictureModel.setPicturePix(picturePix);
                        pictureModel.setPicSheetNames(sheetNames);
                        pictureModel.setCreateUserid(createUserid);
                        String pictureId = pictureService.save(pictureModel);
                        //保存task
                        TaskVo taskVoAdd = new TaskVo();
                        //todo
                        //v1.1
                        taskVoAdd.setEmailSubject(emailSubject == null ? "" : emailSubject);
                        taskVoAdd.setEmailContent(emailContent == null ? "" : emailContent);
                        taskVoAdd.setIsSendEmail(emailOption == null ? "0" : "1");//1代表发送email
                        taskVoAdd.setIsSendExcel(emailIsSendExcel == null ? "0" : "1");//1代表发送Excel
                        taskVoAdd.setIsSendPicture(emailIsSendPicture == null ? "0" : "1");//1代表发送图片
                        taskVoAdd.setIsSendYixin(isSendYixin == null ? "0" : "1");//1代表发送易信
                        taskVoAdd.setYixinReceivers(yixinNames == null ? "" : yixinNames);
                        //v1.1
                        taskVoAdd.setTaskType(city.getBelongType());
                        taskVoAdd.setDataSourceId(dataSource);
                        taskVoAdd.setEmailId(emailRule);
                        taskVoAdd.setTaskDetail(taskDetailModel);
                        taskVoAdd.setExcelId(excelId);
                        taskVoAdd.setPictureId(pictureId);
                        taskVoAdd.setTaskModelName(taskName);
                        taskVoAdd.setCreateUserid(createUserid);
                        taskService.save(taskVoAdd);
                    } else {
                        msg = "名称已存在";
                    }

                }
                //重新展现
                //得到用户对应的任务对象
                TaskModel taskModel = new TaskModel();
                taskModel.setCreateUserid(systemUserModel.getUserModelId());
                List<TaskModel> taskModelList = taskService.queryList(taskModel);

                //得到用户的任务详情对象
                List<TaskDetailModel> taskDetailModelList = new ArrayList<TaskDetailModel>();
                if (taskModelList != null) {
                    for (TaskModel taskModel1 : taskModelList) {
                        TaskDetailModel taskDetailModel1 = taskDetailService.querySingleResult(taskModel1.getTaskDetailId());
                        taskDetailModelList.add(taskDetailModel1);
                    }
                }
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("taskList", taskDetailModelList);
                data.put("msg", msg);
                return new ModelAndView("taskManager", data);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            //没有登录。。。。跳回login
            return new ModelAndView("login", null);
        }
    }

    @RequestMapping(value = "taskAlter", method = RequestMethod.POST)
    @Transactional
    public ModelAndView taskAlter(HttpSession session, HttpServletRequest request, @RequestParam("alterExcelFile") MultipartFile[] files) {

        UserModel systemUserModel = new UserModel();
        String msg = "";
        boolean isSave = true;
        try {
            Object o = session.getAttribute("userInfo");

            if (o != null) {
                systemUserModel = (UserModel) o;
                String taskName = request.getParameter("taskAliasName");
                String cronExpression = request.getParameter("alterCronExpression");//@分割
                String taskDesc = request.getParameter("alterTaskDesc");
                String isAutoRun = request.getParameter("isAutoRun");
                String dataSource = request.getParameter("alterDataSource");//"c465317882254dcf8806d0edc67386a1";//request.getParameter("dataSource");//todo
                String emailRule = request.getParameter("alterEmailRule");//"23bfcae58e4e43b69fbff07acc332144";//request.getParameter("emailRule");//todo
                String sheetNames = request.getParameter("alterSheetNames");
                String picturePix = "200";//request.getParameter("picturePix");
                //v1.1补充
                String emailOption = request.getParameter("alterIsSendEmail");
                String emailSubject = request.getParameter("alterEmailSubject");
                String emailContent = request.getParameter("alterEmailContent");
                String emailIsSendExcel = request.getParameter("alterIsSendExcel");
                String emailIsSendPicture = request.getParameter("alterIsSendPicture");

                String isSendYixin = request.getParameter("alterIsSendYixin");
                String yixinNames = request.getParameter("alterYixinNames");

                String excelId = request.getParameter("excelId");
                String  taskStatus=request.getParameter("taskStatus");

                if (emailOption != null) {
                    if (StringUtils.isEmpty(emailSubject)) {
                        msg = "邮件主题不能为空";
                        isSave = false;
                    }
                    if (StringUtils.isEmpty(emailContent)) {
                        msg = "邮件内容不能为空";
                        isSave = false;
                    }
                }

                if (isSendYixin != null) {
                    if (StringUtils.isEmpty(yixinNames)) {
                        msg = "易信接收人不能为空";
                        isSave = false;
                    }
                }
                //v1.1


                //sheetNames
                if (StringUtils.isEmpty(sheetNames)) {
                    msg = "sheet名称不为能空";
                    isSave = false;
                }
                //文件判断
                List<String> sqlList = new ArrayList<String>();
                boolean isExcelFileChanged = true;
                if (null == files || files[0].getOriginalFilename().isEmpty()) {
                    isExcelFileChanged = false;
                    //判断sheetNames 是否存在
                    if (StringUtils.isEmpty(sheetNames)) {
                        msg = "sheet名称不为能空";
                        isSave = false;
                    } else {
                        //检测sheet名称是否存在,如果返回成功，返回map 包括 table 字段
                        //检测是否是Excel文件格式
                        ResultDto resultDto = null;
                        String[] sheetNamesTmp = sheetNames.split("\\*");
                        List<String> sheetListTmp = new ArrayList<String>();
                        for (String tmp : sheetNamesTmp) {
                            sheetListTmp.add(tmp);
                        }
                        //得到原始的文件---todo---
                        String excelPath=excelService.querySingleResult(excelId).getExcelPath();
                        InputStream inputStream=new FileInputStream(new File(excelPath));
                        resultDto = DataUtils.isSheetNamesExist(inputStream, sheetListTmp);
                        if (resultDto.getStatus().equals(ResultInfo.failure)) {
                            msg = (String) resultDto.getInfo();
                            isSave = false;
                        } else {
                            Map<String, String> sqlMap = (Map<String, String>) resultDto.getInfo();
                            for (Map.Entry entry : sqlMap.entrySet()) {
                                sqlList.add(entry.getValue() + " from " + entry.getKey());
                            }
                        }
                    }
                } else {
                    //检测是否是Excel文件格式
                    ResultDto resultDto = DataUtils.isFileFormatOk(files[0].getInputStream());
                    if (resultDto.getStatus().equals(ResultInfo.failure)) {
                        msg = (String) resultDto.getInfo();
                        isSave = false;
                    }
                    if (StringUtils.isEmpty(sheetNames)) {
                        msg = "sheet名称不为能空";
                        isSave = false;
                    } else {
                        //检测sheet名称是否存在,如果返回成功，返回map 包括 table 字段
                        String[] sheetNamesTmp = sheetNames.split("\\*");
                        List<String> sheetListTmp = new ArrayList<String>();
                        for (String tmp : sheetNamesTmp) {
                            sheetListTmp.add(tmp);
                        }
                        resultDto = DataUtils.isSheetNamesExist(files[0].getInputStream(), sheetListTmp);
                        if (resultDto.getStatus().equals(ResultInfo.failure)) {
                            msg = (String) resultDto.getInfo();
                            isSave = false;
                        } else {
                            Map<String, String> sqlMap = (Map<String, String>) resultDto.getInfo();
                            for (Map.Entry entry : sqlMap.entrySet()) {
                                sqlList.add(entry.getValue() + " from " + entry.getKey());
                            }
                        }
                        // Excel中表名和字段在数据库是否存在
                        DataSourceModel dsm = new DataSourceModel();
                        dsm.setIsDeleted("0");
                        dsm.setDataSourceModelId(dataSource);
                        dsm = jdbcDao.querySingleResult(dsm);
                        for (String sql : sqlList) {
                            resultDto = DBUtils.isOracleConectionSuccess(dsm.getDataSourceUrl(), dsm.getUserName(), dsm.getDsPassword(), null, sql);
                            if (resultDto.getStatus().equals(ResultInfo.failure)) {
                                isSave = false;
                                msg = (String) resultDto.getInfo();
                                break;
                            }
                        }
                    }
                }

                //taskDetailModel 判断
                TaskDetailModel taskDetailModel = new TaskDetailModel();

                //判断是否为空
                if (StringUtils.isEmpty(taskName)) {
                    msg = "任务名称不为能空";
                    isSave = false;
                } else {
                    taskDetailModel.setTaskAliasName(taskName);
                }
                if (StringUtils.isEmpty(cronExpression)) {
                    msg = "时间表达式不能为空";
                    isSave = false;
                } else {
                    try {
                        //是否是Cron表达式
                        for (String cron : cronExpression.split("@")) {
                            //表达式调度构建器
                            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
                        }
                        //判断是否存在且合理，cron在一个地市间隔为3分钟
                        List<TaskDetailModel> taskDetailModelList = taskService.getAllTaskDetailByCityId(systemUserModel.getCity());
                        String taskDetailId=request.getParameter("taskDetailId");
                        DataUtils.iteratorDelete(taskDetailModelList.iterator(),taskDetailId);
                        if (taskDetailModelList != null && taskDetailModelList.size() > 0) {
                            boolean isValid = true;
                            ResultDto resultDto = new ResultDto();
                            for (String cron : cronExpression.split("@")) {
                                resultDto = DateUtils.isCronNoExistAndIsLegal(taskDetailModelList, cron);
                                if (resultDto.getStatus() == ResultInfo.failure) {
                                    msg = cron + " " + (String) resultDto.getInfo();
                                    isSave = false;
                                    break;
                                }
                            }
                        }
                        taskDetailModel.setCronExpression(cronExpression);
                    } catch (Exception ex) {
                        LOG.error(ex.getMessage());
                        msg = "Cron表达式错误";
                        isSave = false;
                    }
                }
                taskDetailModel.setTaskDesc(taskDesc);
                taskDetailModel.setIsAutoRun(isAutoRun);
                taskDetailModel.setTaskStatus(taskStatus);

                City city = new City();
                city.setCityId(systemUserModel.getCity());
                city = jdbcDao.querySingleResult(city);
                taskDetailModel.setTaskGroupName(city.getCityName());

                //任务数限制
//                int userTaskNumsLimit = Integer.parseInt(ConfigUtils.getStringValue("userTaskNumsLimit"));
//                TaskModel taskModellimit = new TaskModel();
//                taskModellimit.setIsDeleted("0");
//                taskModellimit.setCreateUserid(systemUserModel.getUserModelId());
//                List<TaskModel> taskModelListlimit = jdbcDao.queryList(taskModellimit);
//                if (taskModelListlimit.size() > 0) {
//                    if (userTaskNumsLimit == taskModelListlimit.size()) {
//                        msg = "任务数已达到最大值";
//                        isSave = false;
//                    }
//                }

                if (isSave) {
                    //文件保存
                    String fileName = null; //原始文件名
                    String filePath = null; //完整的文件路径
                    String createUserid = systemUserModel.getUserModelId(); //创建用户ID
                    String excelName = null;//修改后的文件名 createUserId_filename

                    // Root Directory.
                    String uploadRootPath = request.getRealPath("/") + "upload";
                    uploadRootPath = ConfigUtils.getStringValue("excelTemplateAddress");
                    File uploadRootDir = new File(uploadRootPath);
                    // Create directory if it not exists.
                    if (!uploadRootDir.exists()) {
                        uploadRootDir.mkdirs();
                    }
                    List<File> uploadedFiles = new ArrayList<File>();

                    //如果存在文件改变
                    if (isExcelFileChanged) {
                        for (int i = 0; i < files.length; i++) {
                            MultipartFile file = files[i];
                            // Client File Name
                            String name = file.getOriginalFilename();
                            fileName = name;
                            LOG.info("Client File Name = " + name);
                            if (name != null && name.length() > 0) {
                                try {
                                    byte[] bytes = file.getBytes();
                                    // Create the file on server
                                    filePath = uploadRootDir.getAbsolutePath() + File.separator + createUserid + "_" + DateUtils.timestampToDataString(System.currentTimeMillis()) + "_" + name;
                                    excelName = createUserid + "_" + DateUtils.timestampToDataString(System.currentTimeMillis()) + "_" + name;
                                    File serverFile = new File(filePath);
                                    // Stream to write data to file in server.
                                    BufferedOutputStream stream = new BufferedOutputStream(
                                            new FileOutputStream(serverFile));
                                    stream.write(bytes);
                                    stream.close();
                                    uploadedFiles.add(serverFile);
                                    LOG.info("Write file: " + serverFile);
                                } catch (Exception e) {
                                    LOG.error(e.getMessage());
                                    LOG.error("Error Write file: " + name);
                                }
                            }
                        }
                        //Excel store to DB
                        ExcelModel excelModel = new ExcelModel();
                        excelModel.setExcelPath(filePath);
                        excelModel.setTemplateName(fileName);
                        excelModel.setExcelName(excelName);
                        excelModel.setCreateUserid(createUserid);
                        StringBuffer stringBuffer = new StringBuffer();
                        for (String sql : sqlList) {
                            stringBuffer.append(sql + "$");
                        }
                        String sqlDb = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                        excelModel.setExcelTableFields(sqlDb);
                        //excelModel.setSheetNames(sheetNames);

                        ExcelVo excelVo = new ExcelVo();
                        excelVo.setExcelName(excelName);
                        excelId = null;
                        if (!excelService.isExist(excelVo)) {
                            excelId = excelService.save(excelModel);
                        } else {
                            msg = "名称已存在";
                        }
                    }

                    //保存图片的分辨率以及sheet页名称
                    String pictureId=request.getParameter("pictureId");
                    PictureModel pictureModel = pictureService.querySingleResult(pictureId);
                    pictureModel.setPicturePix(picturePix);
                    pictureModel.setPicSheetNames(sheetNames);
                    pictureModel.setCreateUserid(createUserid);
                    pictureService.update(pictureModel);

                    //删除原来的task
                    String taskId=request.getParameter("taskId");
                    taskService.delete(taskId);

                    //保存task
                    TaskVo taskVoAdd = new TaskVo();
                    //todo
                    //v1.1
                    taskVoAdd.setEmailSubject(emailSubject == null ? "" : emailSubject);
                    taskVoAdd.setEmailContent(emailContent == null ? "" : emailContent);
                    taskVoAdd.setIsSendEmail(emailOption == null ? "0" : "1");//1代表发送email
                    taskVoAdd.setIsSendExcel(emailIsSendExcel == null ? "0" : "1");//1代表发送Excel
                    taskVoAdd.setIsSendPicture(emailIsSendPicture == null ? "0" : "1");//1代表发送图片
                    taskVoAdd.setIsSendYixin(isSendYixin == null ? "0" : "1");//1代表发送易信
                    taskVoAdd.setYixinReceivers(yixinNames == null ? "" : yixinNames);
                    //v1.1
                    taskVoAdd.setTaskType(city.getBelongType());
                    taskVoAdd.setDataSourceId(dataSource);
                    taskVoAdd.setEmailId(emailRule);
                    taskVoAdd.setTaskDetail(taskDetailModel);
                    taskVoAdd.setExcelId(excelId);
                    taskVoAdd.setPictureId(pictureId);
                    taskVoAdd.setTaskModelName(taskName);
                    taskVoAdd.setCreateUserid(createUserid);
                    taskService.save(taskVoAdd);


                }
                //重新展现
                //得到用户对应的任务对象
                TaskModel taskModel = new TaskModel();
                taskModel.setCreateUserid(systemUserModel.getUserModelId());
                List<TaskModel> taskModelList = taskService.queryList(taskModel);

                //得到用户的任务详情对象
                List<TaskDetailModel> taskDetailModelList = new ArrayList<TaskDetailModel>();
                if (taskModelList != null) {
                    for (TaskModel taskModel1 : taskModelList) {
                        TaskDetailModel taskDetailModel1 = taskDetailService.querySingleResult(taskModel1.getTaskDetailId());
                        taskDetailModelList.add(taskDetailModel1);
                    }
                }
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("taskList", taskDetailModelList);
                data.put("msg", msg);
                return new ModelAndView("taskManager", data);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            //没有登录。。。。跳回login
            return new ModelAndView("login", null);
        }
    }

    @RequestMapping(value = "loadDataBase", method = RequestMethod.POST)
    @ResponseBody
    public List<List<String>> loadDataBase(HttpSession session, HttpServletRequest request) {
        UserModel systemUserModel = new UserModel();
        Object o = session.getAttribute("userInfo");
        if (o != null) {
            systemUserModel = (UserModel) o;
            DataSourceModel dataSourceModel = new DataSourceModel();
            dataSourceModel.setCreateUserid(systemUserModel.getUserModelId());
            List<DataSourceModel> dataSourceModelList = dataSourceService.queryList(dataSourceModel);
            List<List<String>> list = new ArrayList<List<String>>();
            if (dataSourceModelList != null) {
                for (DataSourceModel dataSourceModel1 : dataSourceModelList) {
                    List<String> tmpList = new ArrayList<String>();
                    tmpList.add(dataSourceModel1.getDataSourceModelId());
                    tmpList.add(dataSourceModel1.getDataSourceName());
                    list.add(tmpList);
                }
            }
            return list;
        } else {
            return null;
        }
    }

    @RequestMapping(value = "loadEmail", method = RequestMethod.POST)
    @ResponseBody
    public List<List<String>> loadEmail(HttpSession session, HttpServletRequest request) {
        UserModel systemUserModel = new UserModel();
        Object o = session.getAttribute("userInfo");
        if (o != null) {
            systemUserModel = (UserModel) o;
            EmailModel emailModel = new EmailModel();
            emailModel.setCreateUserid(systemUserModel.getUserModelId());
            List<EmailModel> emailModelList = emailService.queryList(emailModel);
            List<List<String>> list = new ArrayList<List<String>>();
            if (emailModelList != null) {
                for (EmailModel emailModel1 : emailModelList) {
                    List<String> tmpList = new ArrayList<String>();
                    tmpList.add(emailModel1.getEmailModelId());
                    tmpList.add(emailModel1.getEmailName());
                    list.add(tmpList);
                }
            }
            return list;
        } else {
            return null;
        }

    }
    //

    /**
     * 获取任务详情
     *
     * @return
     */
    @RequestMapping(value = "lookTaskDetail", method = RequestMethod.GET)
    @ResponseBody
    public String lookTaskDetail(HttpServletRequest request) {
        String taskDetailId = request.getParameter("taskDetailId");

        try {
            TaskModel taskModel = new TaskModel();
            taskModel.setIsDeleted("0");
            taskModel.setTaskDetailId(taskDetailId);
            taskModel = jdbcDao.querySingleResult(taskModel);
            TaskVo taskVo = taskService.getTaskVoByTaskId(taskModel.getTaskModelId());
            return JSON.toJSONString(taskVo);
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            return "error";
        }
    }


    @RequestMapping(value = "runOnce", method = RequestMethod.GET)
    @ResponseBody
    public String runOnceScheduleJob(HttpServletRequest request) {
        String taskDetailId = request.getParameter("taskDetailId");
        try {
            //待执行还是执行中
            TaskDetailModel taskDetailModel = taskDetailService.querySingleResult(taskDetailId);
            TaskModel taskModel = new TaskModel();
            taskModel.setTaskDetailId(taskDetailId);
            taskModel = jdbcDao.querySingleResult(taskModel);
            String taskId = taskModel.getTaskModelId();
            jobService.runOnce(taskId);
            return "执行一次结束";

        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            return "执行一次失败,请刷新页面";
        }
    }


    @RequestMapping(value = "run", method = RequestMethod.GET)
    public String run(HttpServletRequest request) {

        String taskDetailId = request.getParameter("taskDetailId");
        try {
            //待执行
            TaskDetailModel taskDetailModel = taskDetailService.querySingleResult(taskDetailId);
            TaskModel taskModel = new TaskModel();
            taskModel.setTaskDetailId(taskDetailId);
            taskModel = jdbcDao.querySingleResult(taskModel);
            String taskId = taskModel.getTaskModelId();
            JobKey jobKey = JobKey.jobKey(taskDetailModel.getTaskName(), taskDetailModel.getTaskGroupName());
            if (scheduler.checkExists(jobKey)) {
                scheduleJobService.delete(taskId);
            }
            scheduleJobService.insert(taskService.getTaskVoByTaskId(taskId));

            Criteria criteria = Criteria.update(TaskDetailModel.class).where("taskDetailModelId", new Object[]{taskDetailModel.getTaskDetailModelId()}).set("taskStatus", "1");
            jdbcDao.update(criteria);
            return "redirect:/taskIntoPage";
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            return "redirect:/taskIntoPage";
        }
    }

    /**
     * 暂停
     *
     * @return
     */
    @RequestMapping(value = "pauseTask", method = RequestMethod.GET)
    public String pauseScheduleJob(HttpServletRequest request) {
        String taskDetailId = request.getParameter("taskDetailId");
        try {
            TaskDetailModel taskDetailModel = taskDetailService.querySingleResult(taskDetailId);
            TaskModel taskModel = new TaskModel();
            taskModel.setTaskDetailId(taskDetailId);
            taskModel = jdbcDao.querySingleResult(taskModel);
            String taskId = taskModel.getTaskModelId();
            if (taskDetailModel.getTaskStatus().equals("999")) {
                return "redirect:/taskIntoPage";
            }
            JobKey jobKey = JobKey.jobKey(taskDetailModel.getTaskName(), taskDetailModel.getTaskGroupName());
            boolean isError = false;
            if (scheduler.checkExists(jobKey)) {
                taskService.pauseTask(taskId);
            } else {
                scheduleJobService.insert(taskService.getTaskVoByTaskId(taskId));
                isError = true;
            }


            Criteria criteria = Criteria.update(TaskDetailModel.class).where("taskDetailModelId", new Object[]{taskDetailModel.getTaskDetailModelId()}).set("taskStatus", isError ? "1" : "2");
            jdbcDao.update(criteria);
            return "redirect:/taskIntoPage";
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            return "redirect:/taskIntoPage";
        }
    }

    /**
     * 恢复
     *
     * @return
     */
    @RequestMapping(value = "resumeTask", method = RequestMethod.GET)
    public String resumeScheduleJob(HttpServletRequest request) {
        String taskDetailId = request.getParameter("taskDetailId");
        try {
            TaskDetailModel taskDetailModel = taskDetailService.querySingleResult(taskDetailId);
            TaskModel taskModel = new TaskModel();
            taskModel.setTaskDetailId(taskDetailId);
            taskModel = jdbcDao.querySingleResult(taskModel);
            String taskId = taskModel.getTaskModelId();
            JobKey jobKey = JobKey.jobKey(taskDetailModel.getTaskName(), taskDetailModel.getTaskGroupName());
            if (scheduler.checkExists(jobKey)) {
                taskService.resumeTask(taskId);
            } else {
                scheduleJobService.insert(taskService.getTaskVoByTaskId(taskId));
            }
            Criteria criteria = Criteria.update(TaskDetailModel.class).where("taskDetailModelId", new Object[]{taskDetailModel.getTaskDetailModelId()}).set("taskStatus", "1");
            jdbcDao.update(criteria);

            return "redirect:/taskIntoPage";
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            return "redirect:/taskIntoPage";
        }
    }

    @RequestMapping(value = "taskDelete", method = RequestMethod.GET)
    public String taskDelete(HttpServletRequest request) {
        String taskDetailId = request.getParameter("taskDetailId");
        try {
            TaskDetailModel taskDetailModel = taskDetailService.querySingleResult(taskDetailId);
            TaskModel taskModel = new TaskModel();
            taskModel.setTaskDetailId(taskDetailId);
            taskModel = jdbcDao.querySingleResult(taskModel);
            String taskId = taskModel.getTaskModelId();
            taskService.delete(taskId);

            return "redirect:/taskIntoPage";
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            return "redirect:/taskIntoPage";
        }
    }
    @RequestMapping(value = "downExcelTemplate", method = RequestMethod.GET)
    @ResponseBody
    public void  downExcelTemplate(HttpServletRequest request, HttpServletResponse response) throws  Exception{
        //得到要下载的文件名
        String taskDetailId = request.getParameter("taskDetailId");
        if (taskDetailId.isEmpty()) {
            return;
        }
        //得到要下载的文件
        TaskModel taskModel=new TaskModel();
        taskModel.setTaskDetailId(taskDetailId);
        taskModel.setIsDeleted("0");
        List<TaskModel> taskModelList=taskService.queryList(taskModel);
        ExcelModel excelModel=excelService.querySingleResult(taskModelList.get(0).getExcelId());
        String fileRealPath = excelModel.getExcelPath();
        LOG.info("下载的文件名完整路径:" + fileRealPath);
        //设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(excelModel.getTemplateName(), "UTF-8"));
        //读取要下载的文件，保存到文件输入流
        FileInputStream in = new FileInputStream(fileRealPath);
        //创建输出流
        OutputStream out = response.getOutputStream();
        try {

            //创建缓冲区
            byte buffer[] = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区当中
            while((len=in.read(buffer))>0){
                //输出缓冲区的内容到浏览器，实现文件下载
                out.write(buffer, 0, len);
            }
            //关闭文件输入流
            in.close();
            //关闭输出流
            out.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
            }
        }
    }

    //
//    @RequestMapping(value = "queryTaskInfo", method = RequestMethod.POST)
//    @ResponseBody
//    public String queryTaskInfo(HttpServletRequest request) {
//        String taskDetail = DataUtils.getJsonFromRequest(request);
//        TaskDetailModel taskDetailModeltmp = JSON.parseObject(taskDetail, TaskDetailModel.class);
//        String taskDetailId = request.getParameter("taskDetailId");
//        try {
//            TaskDetailModel taskDetailModel = taskDetailService.querySingleResult(taskDetailId);
//            TaskModel taskModel = new TaskModel();
//            taskModel.setTaskDetailId(taskDetailId);
//            taskModel = jdbcDao.querySingleResult(taskModel);
//            String taskId = taskModel.getTaskModelId();
//            taskService.delete(taskId);
//
//            return "redirect:/taskIntoPage";
//        } catch (Exception ex) {
//            LOG.error(ex.getMessage());
//            return "redirect:/taskIntoPage";
//        }
//    }

}
